package com.eric.study.reactor.service;

import com.eric.study.reactor.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * <p> UserServiceImpl.
 *
 * <p>
 * change history:
 *
 * <pre>
 * date         defect       person          comments
 * --------------------------------------------------------------------------------
 * 2023/9/20    ********     Qiheng Zhang    create file.
 * </pre>
 *
 * @author Qiheng Zhang
 * @date 2023/9/20 15:27
 * @copyright 2023, FA Software (Shanghai) Co., Ltd. All Rights Reserved.
 * @since 1.0.0
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    // 模拟存储数据集合
    private final Map<Integer, User> userMap = new HashMap<>();

    public UserServiceImpl() {
        this.userMap.put(1, new User("Eric", "男性", 24));
        this.userMap.put(2, new User("Mary", "女性", 24));
        this.userMap.put(3, new User("Karry", "女性", 18));
    }

    @Override
    public Mono<User> getUserById(int id) {
        log.info("获取指定用户：{}", id);
        return Mono.justOrEmpty(this.userMap.get(id));
    }

    @Override
    public Flux<User> allUser() {
        log.info("获取所有用户");
        return Flux.fromIterable(this.userMap.values());
    }

    @Override
    public Mono<Void> addUser(Mono<User> user) {
        log.info("新增用户：{}", user);
        return user.doOnNext(person -> this.userMap.put(userMap.size() + 1, person)).then();
    }
}
